<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";

import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount, watch } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { useUserStoreHook } from "@/store/modules/user";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import { ReImageVerify } from "@/components/ReImageVerify";
// import Lock from "@iconify-icons/ri/lock-fill";
import Lock from "~icons/ant-design/lock-filled";
// import User from "@iconify-icons/ri/user-3-fill";
import User from "~icons/ant-design/user-outlined";
// import Keyhole from "~icons/ant-design/shield-keyhole-line";
import Keyhole from "~icons/ant-design/check-square-outlined";
import { setToken } from "@/utils/auth";
import { addPathMatch } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const imgCode = ref("");
const disabled = ref(false);

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "admin",
  password: "admin123",
  verifyCode: ""
});

watch(imgCode, value => {
  useUserStoreHook().SET_VERIFYCODE(value);
});
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      setToken({
        username: "admin",
        roles: ["admin"],
        accessToken: "eyJhbGciOiJIUzUxMiJ9.admin"
      } as any);
      // 全部采取静态路由模式
      usePermissionStoreHook().handleWholeMenus([]);
      addPathMatch();
      router.push("/");
      message("登录成功", { type: "success" });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

// const onLogin = async (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   await formEl.validate(valid => {
//     if (valid) {
//       loading.value = true;
//       useUserStoreHook()
//         .loginByUsername({
//           username: ruleForm.username,
//           password: ruleForm.password
//         })
//         .then(res => {
//           if (res.success) {
//             // 获取后端路由
//             return initRouter().then(() => {
//               disabled.value = true;
//               router
//                 .push(getTopMenu(true).path)
//                 .then(() => {
//                     message("登录成功", { type: "success" });
//                 })
//                 .finally(() => (disabled.value = false));
//             });
//           } else {

//             message("登录失败", { type: "error" });
//           }
//         })
//         .finally(() => (loading.value = false));
//     }
//   });
// };

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="login_box">
      <div class="login-form">
        <!-- <avatar class="avatar" /> -->
        <!-- <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion> -->
        <img class="logo" src="../../assets/img/logo.png" alt="" />
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="loginRules"
          size="large"
        >
          <Motion :delay="100">
            <el-form-item
              :rules="[
                {
                  required: true,
                  message: '请输入账号',
                  trigger: 'blur'
                }
              ]"
              prop="username"
            >
              <el-input
                v-model="ruleForm.username"
                clearable
                placeholder="账号"
                :prefix-icon="useRenderIcon(User)"
              />
            </el-form-item>
          </Motion>

          <Motion :delay="150">
            <el-form-item prop="password">
              <el-input
                v-model="ruleForm.password"
                clearable
                show-password
                placeholder="密码"
                :prefix-icon="useRenderIcon(Lock)"
              />
            </el-form-item>
          </Motion>

          <Motion :delay="200">
            <el-form-item prop="verifyCode">
              <el-input
                v-model="ruleForm.verifyCode"
                clearable
                placeholder="请输入验证码"
                :prefix-icon="useRenderIcon(Keyhole)"
              >
                <template v-slot:append>
                  <ReImageVerify v-model:code="imgCode" />
                </template>
              </el-input>
            </el-form-item>
          </Motion>

          <Motion :delay="250">
            <el-button
              class="button"
              size="default"
              type="primary"
              :disabled="disabled"
              :loading="loading"
              @click="onLogin(ruleFormRef)"
            >
              立即登录
            </el-button>
          </Motion>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
:deep(.el-input) {
  width: 100%;
}
</style>
